package com.pn.exception;


import com.pn.exception.BaseException;
import com.pn.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常现象：{}",ex.getMessage());
        return Result.err(Result.CODE_ERR_BUSINESS,ex.getMessage());
    }

    /*
     * 处理sql异常现象，用户名重复的时候
     * */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + "已存在";
            return Result.err(Result.CODE_ERR_BUSINESS,ex.getMessage());
        }else{
            return Result.err(Result.CODE_ERR_BUSINESS,"未知错误");
        }
    }
}
